package com.jh.user.service;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.TokenUtil;
import com.jh.user.business.BrandManageBusiness;
import com.jh.user.business.ChannelRateBusiness;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.pojo.*;
import com.jh.user.pojo.enums.ChannelMerType;
import com.jh.user.pojo.enums.PayType;
import com.jh.user.util.Commons;
import com.jh.user.util.CommonsUtil;
import com.jh.user.util.ObjectUtils;
import com.jh.user.util.Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Controller
public class ChannelService {


	private static final Logger LOG = LoggerFactory.getLogger(ChannelService.class);

	@Autowired
	private ChannelRateBusiness  channelRateBusiness;


	@Autowired
	private UserLoginRegisterBusiness  userLoginRegisterBusiness;

	@Autowired
	private BrandManageBusiness  brandMangeBusiness;


	@Autowired
	Util util;



	/**创建一个渠道*/
	@RequestMapping(method= POST,value="/v1.0/user/channel/add")
	public @ResponseBody Object addChannel(@RequestParam(value = "channel_tag") String channelTag,
										   @RequestParam(value = "channel_no", defaultValue = "", required=false) String channelNo,
										   @RequestParam(value = "name") String name,
										   @RequestParam(value = "sub_channel_tag", defaultValue = "", required=false) String subChannelTag,
										   @RequestParam(value = "sub_name",  defaultValue = "", required=false) String subName,
										   @RequestParam(value = "single_min_limit", defaultValue = "", required=false) String singleMinLimit,
										   @RequestParam(value = "single_max_limit", defaultValue = "", required=false) String singleMaxLimit,
										   @RequestParam(value = "every_day_max_limit", defaultValue = "", required=false) String everyDayMaxLimit,
										   @RequestParam(value = "start_time", defaultValue = "", required=false) String startTime,
										   @RequestParam(value = "end_time", defaultValue = "", required=false) String endTime){
		try {
			Channel channel = channelRateBusiness.findChannelByTag(subChannelTag);
			if(channel == null){

				channel  = new Channel();

			}

			channel.setChannelNo(channelNo);
			channel.setChannelTag(channelTag);
			channel.setCreateTime(new Date());
			channel.setName(name);
			channel.setSubName(subName);
			channel.setSubChannelTag(subChannelTag);
			if(endTime != null && !endTime.equalsIgnoreCase("")){
				try {
					DateUtil.getHHMMSSDateFormat(endTime);
				} catch (Exception e) {
					return CommonsUtil.returnError("添加通道失败,通道结束使用时间不能为:"+ endTime +",格式应为00:00:00");
				}
			}
			channel.setEndTime(endTime);
			if(startTime != null && !startTime.equalsIgnoreCase("")){
				try {
					DateUtil.getHHMMSSDateFormat(startTime);
				} catch (Exception e) {
					return CommonsUtil.returnError("添加通道失败,通道开始使用时间不能为:"+ startTime +",格式应为00:00:00");
				}
			}
			channel.setStartTime(startTime);
			if(everyDayMaxLimit != null && !everyDayMaxLimit.equalsIgnoreCase("")){
				channel.setEveryDayMaxLimit(new BigDecimal(everyDayMaxLimit));
			}

			if(singleMaxLimit != null && !singleMaxLimit.equalsIgnoreCase("")){
				channel.setSingleMaxLimit(new BigDecimal(singleMaxLimit));
			}

			if(singleMinLimit != null && !singleMinLimit.equalsIgnoreCase("")){
				channel.setSingleMinLimit(new BigDecimal(singleMinLimit));
			}

			channel = channelRateBusiness.mergeChannel(channel);
			return CommonsUtil.returnSuccess(channel);
		}catch (Exception e){
			return CommonsUtil.returnError("ChannelService.addChannel, 创建渠道失败");
		}

	}

	/**修改渠道信息*/
	@RequestMapping(method= POST,value="/v1.0/user/channel/update")
	public @ResponseBody Object addChannel(HttpServletRequest request,
										   /**渠道id*/
										   @RequestParam(value = "channelid") long channelid,
										   /**渠道商家标号 0:反扫；1正扫；2快捷；3公众号；4：隐藏*/
										   @RequestParam(value = "channel_no",  required=false) String channelNo,
										   /**渠道名字*/
										   @RequestParam(value = "name") String name,
										   /**渠道类别如：微信；支付宝；快捷；公众号*/
										   @RequestParam(value = "sub_name",   required=false) String subName,
										   /**是否到余额   0：到余额；1到卡*/
										   @RequestParam(value = "auto_clearing",defaultValue="0",   required=false) String autoclearing,
										   /**通道备注*/
										   @RequestParam(value = "remarks",   required=false) String remarks,
										   /**通道备注*/
										   @RequestParam(value = "extended_field",   required=false) String extendedField,
										   /**单次最低限额*/
										   @RequestParam(value = "single_min_limit",  required=false) String singleMinLimit,
										   /**单次最高额度*/
										   @RequestParam(value = "single_max_limit", required=false) String singleMaxLimit,
										   /**单日最高额度*/
										   @RequestParam(value = "every_day_max_limit",  required=false) String everyDayMaxLimit,
										   /**通道开始可以使用的时间*/
										   @RequestParam(value = "start_time",  required=false) String startTime,
										   /**状态*/
										   @RequestParam(value = "status",  required=false) String status,
										   /**通道结算的时间**/
										   @RequestParam(value = "end_time",  required=false) String endTime,
										   /**成本提现费*/
										   @RequestParam(value = "min_with_draw_fee",defaultValue="1.00",  required=false) BigDecimal minwithdrawFee,
										   /**成本额外费用*/
										   @RequestParam(value = "min_extra_fee", defaultValue="0.00" ,required=false) BigDecimal minextrafee
	){
		Map<String,Object> map = new HashMap<String,Object>();
		Channel channel = channelRateBusiness.findChannelById(channelid);
		if(channel == null){
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_USER_NOT_EXISTED);
			map.put(CommonConstants.RESP_MESSAGE, "通道不存在");
			map.put(CommonConstants.RESULT, channel);
			return map;
		}
		channel.setChannelNo( channelNo!=null&&!channelNo.equals("")?channelNo:channel.getChannelNo());

		channel.setCreateTime(new Date());

		channel.setAutoclearing(autoclearing!=null&&!autoclearing.equals("")?autoclearing:channel.getAutoclearing());
		channel.setStatus(status!=null&&!status.equals("")?status:channel.getStatus());
		channel.setRemarks(remarks!=null&&!remarks.equals("")?remarks:channel.getRemarks());
		channel.setExtendedField(extendedField!=null&&!extendedField.equals("")?extendedField:channel.getExtendedField());
		channel.setName(name!=null&&!name.equals("")?name:channel.getName());
		channel.setSubName(subName!=null&&!subName.equals("")?subName:channel.getSubName());
		if(endTime != null && !endTime.equalsIgnoreCase("")){
			try {
				DateUtil.getHHMMSSDateFormat(endTime);
			} catch (Exception e) {
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "添加通道失败,通道结束使用时间不能为:"+ endTime +",格式应为00:00:00");
				return map;
			}
			channel.setEndTime(endTime);
		}

		if(startTime != null && !startTime.equalsIgnoreCase("")){
			try {
				DateUtil.getHHMMSSDateFormat(startTime);
			} catch (Exception e) {
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "添加通道失败,通道开始使用时间不能为:"+ startTime +",格式应为00:00:00");
				return map;
			}
			channel.setStartTime(startTime);
		}

		if(everyDayMaxLimit != null && !everyDayMaxLimit.equalsIgnoreCase("")){
			channel.setEveryDayMaxLimit(new BigDecimal(everyDayMaxLimit));
		}else{
			channel.setEveryDayMaxLimit(channel.getEveryDayMaxLimit());
		}


		if(singleMaxLimit != null && !singleMaxLimit.equalsIgnoreCase("")){
			channel.setSingleMaxLimit(new BigDecimal(singleMaxLimit));
		}else{
			channel.setSingleMaxLimit(channel.getSingleMaxLimit());
		}



		if(singleMinLimit != null && !singleMinLimit.equalsIgnoreCase("")){
			channel.setSingleMinLimit(new BigDecimal(singleMinLimit));
		}else{
			channel.setSingleMinLimit(channel.getSingleMinLimit());
		}


		channel = channelRateBusiness.mergeChannel(channel);
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, channel);
		return map;
	}
	/**生成一个渠道费率*/
	@RequestMapping(method= POST,value="/v1.0/user/channel/rate/add")
	public @ResponseBody Object addChannelRate(HttpServletRequest request,
											   @RequestParam(value = "user_id",  defaultValue="", required=false) String userId,
											   @RequestParam(value = "brand_id") long brandId,
											   @RequestParam(value = "channel_id") long channelId,
											   @RequestParam(value = "rate") BigDecimal rate,
											   @RequestParam(value = "extra_fee", required=false) BigDecimal extraFee,
											   @RequestParam(value = "grade_rate", required=false) BigDecimal gradeRate){

		BrandRate brandRate=brandMangeBusiness.findRateByBrandAndChannel(brandId,channelId,"0", PayType.TRADE.getValue());
		if(brandRate!=null){
			if(rate.doubleValue()<brandRate.getMinrate().doubleValue()){
				Map map = new HashMap();
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的设置的费率小于该通道的最低费率"+brandRate.getMinrate());
				return map;
			}
			if(rate.doubleValue()>brandRate.getRate().doubleValue()){
				Map map = new HashMap();
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的设置的费率大于该通道的普通会员的费率"+brandRate.getRate());
				return map;
			}

		}else{
			Map map = new HashMap();
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的贴牌未设置初始费率");
			return map;

		}


		ChannelRate channelRate = null;
		if(userId != null && !userId.equalsIgnoreCase("")){
			User user=userLoginRegisterBusiness.queryUserById(Long.parseLong(userId));
			ChannelRate prechannelRate = channelRateBusiness.findChannelRateByUserid(user.getPreUserId(), channelId);
			if(prechannelRate!=null){
				if(prechannelRate.getRate().doubleValue()<rate.doubleValue()){
					Map map = new HashMap();
					map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "添加失败,该费率已经小于他的上级费率"+prechannelRate.getRate());
					return map;
				}
			}else{
				if(brandRate.getRate().doubleValue()<rate.doubleValue()){
					Map map = new HashMap();
					map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "添加失败,该费率已经小于他的上级费率"+prechannelRate.getRate());
					return map;
				}
			}
			channelRate = channelRateBusiness.findChannelRateByUserid(Long.parseLong(userId), channelId);
		}
		if(channelRate == null){

			channelRate = new ChannelRate();

		}


		channelRate.setChannelId(channelId);
		channelRate.setCreateTime(new Date());
		channelRate.setExtraFee(extraFee);
		channelRate.setRate(rate);
		channelRate.setGradeRate(gradeRate);
		channelRate.setBrandId(brandId);
		if(userId != null && !userId.equalsIgnoreCase("")){
			channelRate.setUserId(Long.parseLong(userId));
		}



		channelRate = channelRateBusiness.mergeChannelRate(channelRate);
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, channelRate);
		return map;



	}

	/**生成一个渠道费率*/
	@RequestMapping(method= POST,value="/v1.0/user/channel/grade/rate/add")
	public @ResponseBody Object addChannelGradeRate(HttpServletRequest request,
													@RequestParam(value = "user_id",  defaultValue="", required=false) String userId,
													@RequestParam(value = "brand_id") long brandId,
													@RequestParam(value = "channel_id") long channelId,
													@RequestParam(value = "rate") BigDecimal rate,
													@RequestParam(value = "extra_fee", required=false) BigDecimal extraFee,
													@RequestParam(value = "grade_rate", required=false) BigDecimal gradeRate){
		Map<String,Object> map = new HashMap<String,Object>();
		BrandRate brandRate=brandMangeBusiness.findRateByBrandAndChannel(brandId,channelId,"0", PayType.TRADE.getValue());
		if(brandRate!=null){
			if(rate.doubleValue()<brandRate.getMinrate().doubleValue()){
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的设置的费率小于该通道的最低费率"+brandRate.getMinrate());
				return map;
			}
			if(rate.doubleValue()>brandRate.getRate().doubleValue()){
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的设置的费率大于该通道的普通会员的费率"+brandRate.getRate());
				return map;
			}

		}else{
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的贴牌未设置初始费率");
			return map;

		}

		ChannelRate channelRate = null;
		if(userId != null && !userId.equalsIgnoreCase("")){
			channelRate = channelRateBusiness.findChannelRateByUserid(Long.parseLong(userId), channelId);
		}
		if(channelRate == null){

			channelRate = new ChannelRate();

		}

		channelRate.setChannelId(channelId);
		channelRate.setCreateTime(new Date());
		channelRate.setExtraFee(brandRate.getExtraFee());
		channelRate.setRate(rate);
		channelRate.setGradeRate(brandRate.getGradeRate());
		channelRate.setBrandId(brandId);
		if(userId != null && !userId.equalsIgnoreCase("")){
			channelRate.setUserId(Long.parseLong(userId));
		}

		channelRate = channelRateBusiness.mergeChannelRate(channelRate);
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, channelRate);
		return map;
	}


	/**
	 * 获取渠道标识
	 * @param channelTag
	 * @return
	 */
	@RequestMapping(method= POST,value="/v1.0/user/channel/query")
	public @ResponseBody Object queryChannelByTag(@RequestParam(value = "channel_tag") String channelTag){
		try {
			return CommonsUtil.returnSuccess(channelRateBusiness.findChannelByTag(channelTag));
		}catch (Exception e){
			LOG.error("ChannelService.queryChannelByTag,获取渠道标识异常======" + e.getMessage());
			return CommonsUtil.returnError("获取渠道标识失败！");
		}
	}

	/**
	 * 获取全部渠道信息
	 * @param request
	 * @return
	 */
	@RequestMapping(method= POST,value="/v1.0/user/channel/query/all")
	public @ResponseBody Object queryAllChannel(HttpServletRequest request){
		try {
			return CommonsUtil.returnSuccess(channelRateBusiness.findAllChannel());
		}catch (Exception e){
			LOG.error("ChannelService.queryAllChannel,获取渠道标识异常======" + e.getMessage());
			return CommonsUtil.returnError("获取渠道标识失败！");
		}

	}


	/**传递平台id将所有平台信息和费率都取回来*/
	@RequestMapping(method= POST,value="/v1.0/user/channel/query/all/brandid")
	public @ResponseBody Object queryAllChannelByBrandId(@RequestParam(value = "user_id") long userId,
														 @RequestParam(value = "payType",defaultValue="0", required=false) long payType,
														 String amountMoney,String type){
		try {
			List<Channel> list =  channelRateBusiness.findAllChannel(userId, payType,0,amountMoney,type);
			List<ChannelVO> result = ChannelVO.transform(list);
			return CommonsUtil.returnSuccess(result);
		} catch (Exception e) {
			LOG.error("查询个人费率异常======" + e.getMessage());
			e.printStackTrace();
			return CommonsUtil.returnError("查询个人费率失败！"+e.getMessage());
		}
	}

	/**
	 * 查询指定用户的通道费率信息(NEW)
	 */
	@RequestMapping(method = POST, value = "/v1.0/user/channel/list/user_channel_rate")
	public @ResponseBody Object findUserChannelRate(UserChannelRequest request) {
		if (request.getUserId() == null) {
			return CommonsUtil.returnError("用户id不能为空");
		}
		List<UserChannelRate> channelList = channelRateBusiness.findUserChannelRate(request.getUserId());
		List<UserChannelRate> result = UserChannelRate.transform(channelList);
		return CommonsUtil.returnSuccess(result);
	}

	/**
	 * 修改指定用户通道费率(NEW)
	 * userId: 673859921
	 * channelId: 1
	 * type: 1
	 * rate: 0.5001
	 * extraFee: 2
	 * gradeRate: 0.0058
	 */
	@RequestMapping(method= POST, value="/v1.0/user/channel/rate/update_rate")
	public @ResponseBody Object updateUserChannelRate(UserChannelRequest channelRequest){
		try {
			channelRequest.validation();

			ChannelRate channelRate = channelRateBusiness.updateUserChannelRate(channelRequest);
			if (channelRate == null) {
				return CommonsUtil.returnError("通道费率修改失败");
			}
			channelRate.setChannelMerType(ChannelMerType.of(channelRate.getChannelMerType()).getDesc());
			return CommonsUtil.returnSuccess(channelRate);
		} catch (ServiceException ex) {
			return CommonsUtil.returnError(ex.getMessage());
		}
	}

	/**后台传递平台id将所有平台信息和费率都取回来*/
	@RequestMapping(method= POST,value="/v1.0/user/channel/query/all/brandid/pc")
	public @ResponseBody Object queryAllChannelByBrandIdPC(HttpServletRequest request,
														   @RequestParam(value = "user_id") String suserId,

														   @RequestParam(value = "access_type",defaultValue="1", required=false) String saccesstype
	){
		Map<String,Object> map = new HashMap<String,Object>();
		long userId;
		try {
			if("".equals(suserId)){
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "查询失败,参数userId不能为'"+suserId+"',请检查后重试!");
				return map;
			}
			userId = Long.valueOf(suserId);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询失败,参数userId不能为'"+suserId+"',请检查后重试!");
			return map;
		}
		long accesstype;
		try {
			if("".equals(saccesstype)){
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "查询失败,参数accesstype不能为'"+saccesstype+"',请检查后重试!");
				return map;
			}
			accesstype = Long.valueOf(saccesstype);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询失败,参数accesstype不能为'"+saccesstype+"',请检查后重试!");
			return map;
		}

		User user = userLoginRegisterBusiness.queryUserById(userId);

		List<Channel> channels = channelRateBusiness.findAllChannelByBrandid(user.getBrandId());

		List<Channel> result = new ArrayList<Channel>();
		for(Channel channel : channels){
			Channel temp = channel;
			ChannelRate channelRate = channelRateBusiness.findChannelRateByUserid(userId, channel.getId());
			BrandRate brandRate = null;
			if(channelRate == null){
				brandRate = brandMangeBusiness.findRateByBrandAndChannel(user.getBrandId(), channel.getId(),user.getGrade(), PayType.TRADE.getValue());
				temp.setRate(brandRate.getRate());
				//temp.setWithdrawFee(brandRate.getWithdrawFee());
				if(temp.getId()!=82&&temp.getId()!=90)
					temp.setExtraFee(brandRate.getExtraFee().setScale(2, BigDecimal.ROUND_DOWN));
				temp.setStartTime(temp.getStartTime().substring(0,temp.getStartTime().lastIndexOf(":")));
				temp.setEndTime(temp.getEndTime().substring(0,temp.getEndTime().lastIndexOf(":")));
			}else{
				temp.setRate(channelRate.getRate());
				if(temp.getId()!=82&&temp.getId()!=90)
					temp.setExtraFee(channel.getExtraFee().setScale(2, BigDecimal.ROUND_DOWN));
				temp.setStartTime(temp.getStartTime().substring(0,temp.getStartTime().lastIndexOf(":")));
				temp.setEndTime(temp.getEndTime().substring(0,temp.getEndTime().lastIndexOf(":")));
			}
			result.add(temp);
		}

		if(accesstype==1) {
			List<Channel> channels2=result;
			result = new ArrayList<Channel>();
			for(Channel channel : channels2) {
				if(!channel.getStatus().equals("1")) {
					channel.setChannelNo("4");
					result.add(channel);
				}else {
					result.add(channel);
				}
			}
		}
		Collections.sort(result,new Comparator<Channel>(){
			public int compare(Channel arg0, Channel arg1) {
				return arg1.getChannelNo().compareTo(arg0.getChannelNo());
			}
		});
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, result);
		return map;

	}

	/**获取渠道费率*/
	@RequestMapping(method= POST,value="/v1.0/user/channel/rate/query/brandid")
	public @ResponseBody Object queryChannelRateByBrandid(@RequestParam(value = "brand_id") long brandId, @RequestParam(value = "channel_id") long channelId){
		List<ChannelRate>  channelRate = channelRateBusiness.findChannelRateByBrandid(brandId, channelId);
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, channelRate);
		return map;
	}


	/**修改用户的渠道费率**/
	@RequestMapping(method= POST,value="/v1.0/user/channel/rate/update/userid")
	public @ResponseBody Object queryChannelRateByuserid(@RequestParam(value = "user_id") long userId,
														 @RequestParam(value = "channel_id") long channelId,
														 @RequestParam(value = "rate") String rate,
														 @RequestParam(value = "extra_fee", defaultValue = "0", required=false) String extraFee,
														 @RequestParam(value = "grade_rate", required=false) String gradeRate){
		User user = userLoginRegisterBusiness.queryUserById(userId);
		BrandRate brandRate=brandMangeBusiness.findRateByBrandAndChannel(user.getBrandId(),channelId,"0", PayType.TRADE.getValue());
		if(brandRate!=null){
			if(Double.parseDouble(rate)<brandRate.getMinrate().doubleValue()){
				Map map = new HashMap();
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的设置的费率小于改通道的最低费率"+brandRate.getMinrate());
				return map;
			}
			if(Double.parseDouble(rate)>brandRate.getRate().doubleValue()){
				Map map = new HashMap();
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的设置的费率大于改通道的普通会员的费率"+brandRate.getRate());
				return map;
			}

		}else{
			Map map = new HashMap();
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的贴牌未设置初始费率");
			return map;

		}

		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");

		ChannelRate channelRate = channelRateBusiness.findChannelRateByUserid(userId, channelId);

		if(channelRate == null){
			channelRate = new ChannelRate();
			channelRate.setUserId(userId);
			channelRate.setBrandId(user.getBrandId());
			channelRate.setChannelId(channelId);

		}

		channelRate.setCreateTime(new Date());
		channelRate.setRate(new BigDecimal(rate));

		if(!extraFee.equalsIgnoreCase("")){
			channelRate.setExtraFee(new BigDecimal(extraFee));
		}

		if(!gradeRate.equalsIgnoreCase("")){
			channelRate.setGradeRate(new BigDecimal(gradeRate));
		}

		map.put(CommonConstants.RESULT, channelRateBusiness.mergeChannelRate(channelRate));
		return map;
	}

	/**获取所有渠道费率*/
	@RequestMapping(method= POST,value="/v1.0/user/channel/rate/query/all")
	public @ResponseBody Object queryAllChannelRatesChannelRates(HttpServletRequest request){


		Map map  = new HashMap();
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, channelRateBusiness.findChannelRates());
		return map;
	}

	/**获取渠道费率*/
	@RequestMapping(method= POST,value="/v1.0/user/channel/rate/query/userid")
	public @ResponseBody Object queryChannelRateByuserid(@RequestParam(value = "user_id") long userId, @RequestParam(value = "channel_id") long channelId){
		Map<String,Object> map = new HashMap<String,Object>();
		User user = null;
		try {
			user = userLoginRegisterBusiness.queryUserById(userId);
		} catch (Exception e) {
			LOG.error("/r/n获取用户异常(可能原因:userId无效)=========="+e.getMessage());
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE,"亲.网络异常,请重试");
			return map;
		}

		if(ObjectUtils.isEmpty(user)){
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE,"亲.无该用户数据");
			return map;
		}

		try {
			ChannelRate channelRate = null;
			BrandRate brandRate = null;
			channelRate = channelRateBusiness.findChannelRateByUserid(userId, channelId);
			brandRate = brandMangeBusiness.findRateByBrandAndChannel(user.getBrandId(), channelId,user.getGrade(), PayType.TRADE.getValue());
//			LOG.info("userId=:"+userId+"channelId="+channelId);
			if(ObjectUtils.isEmpty(channelRate)){
				if(ObjectUtils.isEmpty(brandRate)){
					map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE,"亲.没有配置渠道费率哦!");
					return map;
				}
				map.put(CommonConstants.RESULT, brandRate);
			}else{
				channelRate.setExtraFee(brandRate.getExtraFee());
				channelRate.setGradeRate(brandRate.getGradeRate());
				map.put(CommonConstants.RESULT, channelRate);
			}
		} catch (Exception e) {
			LOG.error("/r/n获取渠道费率异常(可能原因:没有配置channel路由)=========="+e.getMessage());
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE,"亲.网络异常,请重试");
			return map;
		}
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;
	}

	/**
	 通过品牌Id查询通道*/
	@RequestMapping(method= POST,value="/v1.0/user/channel/query/brandid")
	public @ResponseBody Object findAllChannelByBrandid(@RequestParam(value = "brand_id") long  brandid){
		List<Channel> resources = channelRateBusiness.findAllChannelByBrandid(brandid);
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, resources);
		return map;
	}

//	/**
//	 * 统一设定直属下级分润
//	 * */
//	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/channel/rate/")
//	public @ResponseBody Object findAllChannelByBrandid(HttpServletRequest request,
//			@RequestParam(value = "brand_id") long  brandid
//			){


	//根据ChannelNo查询通道
	@RequestMapping(method= POST,value="/v1.0/user/channel/channelno")
	public @ResponseBody Object findChannelByChannelNo(@RequestParam(value = "channel_no", defaultValue="3", required=false) String channelNo){
		List<Channel> findChannelByChannelNo = channelRateBusiness.findChannelByChannelNo(channelNo);
		String  channelTags="";
		if(findChannelByChannelNo!=null&&findChannelByChannelNo.size()>0)
			for(Channel channel:findChannelByChannelNo){
				channelTags+=channel.getChannelTag()+",";
			}

		if(channelTags!=null&&!channelTags.equals("")){
			channelTags = channelTags.substring(0, channelTags.length()-1);
		}

		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, channelTags);
		map.put(CommonConstants.RESP_MESSAGE, "成功");

		return map;
	}

	@RequestMapping(method= POST,value="/v1.0/user/channel/find/by/channelid")
	public @ResponseBody Object getChannelByChannelId(@RequestParam(value="channelId")String channelId){
		Map<String,Object> map = new HashMap<>();
		Channel channel = channelRateBusiness.findByChannelId(Long.valueOf(channelId).longValue());
		if(channel == null){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "无该通道信息!");
			return map;
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, channel);
		return map;
	}
	/**
	 * app端查询渠道列表
	 * @param userId
	 * @param
	 * @return
	 */
	@RequestMapping(method=POST,value="/v1.0/user/channel/queryChannelRate")
	public @ResponseBody Object queryChannelRate(BrandRate rate,@RequestParam(value="userId")long userId,@RequestParam(value="amountMoney")String amountMoney,@RequestParam(value="type") String type){
		try {
			List<Channel> list =  channelRateBusiness.findAllChannel(userId, Integer.valueOf(rate.getPayType()),rate.getChannelId(),amountMoney,type);
			return CommonsUtil.returnSuccess(list);
		}catch (Exception e){
			LOG.error("ChannelService.queryChannelRate, 查询渠道异常======" + e.getMessage());
			return CommonsUtil.returnError("查询渠道失败！" + e.getMessage());
		}
	}

	@RequestMapping(method=POST, value="/v1.0/user/channel/queryDefaultChannelRate")
	public @ResponseBody Object queryDefaultChannelRate(@RequestParam(value="userId")long userId,
														@RequestParam(value = "payType") int payType,
														@RequestParam(value = "channelId")long channelId,
														@RequestParam(value = "amountMoney")String amountMoney,
														@RequestParam(value = "type") String type){
		try {
			List<Channel> list =  channelRateBusiness.findAllChannel( userId, payType, channelId, amountMoney, type);
			return CommonsUtil.returnSuccess(list);
		}catch (Exception e){
			LOG.error("ChannelService.queryChannelRate, 查询渠道异常======" + e.getMessage());
			return CommonsUtil.returnError("查询渠道失败！" + e.getMessage());
		}
	}

	/**
	 * 查询费率
	 * @param userId
	 * @param type
	 * @param channelType
	 * @return
	 */
	@RequestMapping(method= POST,value="/v1.0/user/channel/queryRate")
	public @ResponseBody Object findAllChannelRate(@RequestParam(value="userId")long userId,@RequestParam(value="type")long type,@RequestParam(value="channelType")String channelType){
		try {
			ChannelRate channelRate =  channelRateBusiness.findAllChannelRate(userId, type,channelType);
			return CommonsUtil.returnSuccess(channelRate);
		}catch (Exception e){
			LOG.error("ChannelService.queryChannelRate, 查询费率异常======" + e.getMessage());
			return CommonsUtil.returnError("查询费率失败！" + e.getMessage());
		}
	}

	/**
	 * 新增/修改渠道
	 * @param channelRequest
	 * @param bindingResult
	 * @param token
	 * @param operating 0新增，1修改
	 * @param channel
	 * @return
	 */
	@PostMapping(value = "/v1.0/user/channel/saveOfUpdateChannelInfo/{token}")
	public @ResponseBody Object saveOfUpdateChannelInfo(
								@Valid ChannelRequest channelRequest,
							   BindingResult bindingResult,
							   	@PathVariable(value = "token") String token,
							   	@RequestParam(value = "operating") String operating,
								Channel channel) {
		try {
			long userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			return CommonsUtil.returnError("token无效！");
		}
		try {
			if (bindingResult.hasErrors()) {
				StringBuffer res = new StringBuffer();
				List<ObjectError> allErrors = bindingResult.getAllErrors();
				for (ObjectError error : allErrors) {
					res.append(error.getDefaultMessage());
				}
				return CommonsUtil.returnError(res.toString());
			}
			if (null == channelRequest) {
				return CommonsUtil.returnError("无法添加/修改渠道信息！");
			}
			Map<String, Object> resMap = channelRateBusiness.saveOfUpdateChannelInfo(operating, channelRequest, channel);
			if ("0".equals(operating)) {
				return CommonsUtil.returnSuccess(resMap, resMap.get("name") + "添加成功");
			}
			return CommonsUtil.returnSuccess(resMap, resMap.get("name") + "修改成功");
		} catch (Exception e) {
			LOG.error("ChannelService.addChannelInfo添加/修改渠道信息异常！e = " + e.getMessage());
			if (e.getMessage().contains("添加失败")) {
				return CommonsUtil.returnError(e.getMessage());
			}
			if ("0".equals(operating)) {
				return CommonsUtil.returnError("添加渠道信息失败，请稍后再试！");
			}
			if ("1".equals(operating)) {
				return CommonsUtil.returnError("修改渠道信息失败，请稍后再试！");
			}
			return CommonsUtil.returnError("服务器异常，请稍后再试！");
		}
	}

	/**
	 * 后台查询所有通道信息
	 * @param token
	 * @return
	 */
	@PostMapping(value = "/v1.0/user/channel/queryAllChannel/{token}")
	public @ResponseBody Object queryAllChannel(@PathVariable(value = "token") String token) {
		try {
			TokenUtil.getUserId(token);
		} catch (Exception e) {
			return CommonsUtil.returnError("token无效！");
		}
		try {
			List<Map<String, Object>> channelList = channelRateBusiness.queryAllChannel();
			return CommonsUtil.returnSuccess(channelList, "查询成功！");
		} catch (Exception e) {
			return CommonsUtil.returnError("服务器异常，请稍后再试！");
		}
	}

	/**
	 * 总后台-设置公共费率-新增公共费率
	 * @param token
	 * @param brandRateRequest
	 * @return
	 */
	@PostMapping(value = "/v1.0/user/channel/addBrandRate/{token}")
	public @ResponseBody Object addBrandRate(@PathVariable(value = "token") String token,
											 BrandRateRequest brandRateRequest,
											 @RequestParam(value = "brandrate") BigDecimal brandrate) {
	    try {
	        TokenUtil.getUserId(token);
        } catch (Exception e) {
	        return CommonsUtil.returnError("token无效！");
        }
        try {
			brandRateRequest.validation();
			if (null == brandrate) {
			    return CommonsUtil.returnError("贴牌费率不能为空！");
            }
			BrandRate brandRate = channelRateBusiness.addBrandRate(brandRateRequest, brandrate);
			return CommonsUtil.returnSuccess(brandRate, "新增公共费率成功！");
		} catch (ServiceException e) {
        	return CommonsUtil.returnError(e.getMessage());
		} catch (Exception e) {
        	return CommonsUtil.returnError("服务器异常，请稍后再试！");
		}
	}

	/**
	 * 总后台-贴牌管理-设置公共费率-修改贴牌费率
	 * @param token
	 * @param brnadId 贴牌id
	 * @param channelNo 通道id
	 * @param payType 交易方式：1交易，2代还/提现
	 * @param brandRate 贴牌费率
	 * @return
	 */
	@PostMapping(value = "/v1.0/user/channel/editBrandRate/{token}")
	public @ResponseBody Object editBrandRate(@PathVariable(value = "token") String token,
											  @RequestParam(value = "brandId") long brnadId,
											  @RequestParam(value = "channelNo", required = false) String channelNo,
											  @RequestParam(value = "payType", required = false) String payType,
											  @RequestParam(value = "brandRate") BigDecimal brandRate) {
		try {
			TokenUtil.getUserId(token);
		} catch (Exception e) {
			return CommonsUtil.returnError("token无效！");
		}
		try {
			return channelRateBusiness.editBrandRate(brnadId, channelNo, payType, brandRate);
		} catch (Exception e) {
			if (e.getMessage().contains("贴牌费率")) {
				return CommonsUtil.returnError(e.getMessage());
			}
			return CommonsUtil.returnError("服务器异常，请稍后再试！");
		}
	}
}
